package com.jzo2o.customer.service.impl;

import com.jzo2o.api.publics.SmsCodeApi;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.enums.SmsBussinessTypeEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.model.dto.request.InstitutionRegisterReqDTO;
import com.jzo2o.customer.service.IRegisterService;
import com.jzo2o.customer.service.IServeProviderService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class IRegisterServiceImpl implements IRegisterService {

    @Resource
    private IServeProviderService serveProviderService;
    @Resource
    private SmsCodeApi smsCodeApi;
    @Override
    public void register(InstitutionRegisterReqDTO institutionRegisterReqDTO) {

        // 数据校验
        if (StringUtils.isEmpty(institutionRegisterReqDTO.getVerifyCode())) {
            throw new BadRequestException("验证码为空");
        }

        //远程调用publics服务校验验证码是否正确
        boolean verifyResult = smsCodeApi.verify(institutionRegisterReqDTO.getPhone(), SmsBussinessTypeEnum.INSTITION_REGISTER, institutionRegisterReqDTO.getVerifyCode()).getIsSuccess();
        if (!verifyResult) {
            throw new BadRequestException("验证码错误，请重新获取");
        }

        // 注册
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(institutionRegisterReqDTO.getPassword());
        serveProviderService.add(institutionRegisterReqDTO.getPhone(), UserType.INSTITUTION, password);
    }
}
